package com.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.constant.Constant;
import com.demo.entity.DischargeSummary;
import com.demo.entity.DischargeSummaryMedicine;
import com.demo.entity.User;
import com.demo.entity.Vo.DischargeSummaryVo;
import com.demo.entity.from.DischargeSummaryFrom;
import com.demo.jwt.JwtTokenUtil;
import com.demo.mapper.DischargeSummaryMapper;
import com.demo.mapper.PatientMapper;
import com.demo.mapper.UserMapper;
import com.demo.response.Result;
import com.demo.service.IDischargeSummaryMedicineService;
import com.demo.service.IDischargeSummaryService;
import com.demo.service.IMessageService;
import com.demo.util.HeatUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 出院总结表 服务实现类
 * @author zm
 * @since 2020-12
 */
@Service
@Slf4j
public class DischargeSummaryServiceImpl extends ServiceImpl<DischargeSummaryMapper, DischargeSummary> implements IDischargeSummaryService {
    @Resource
    DischargeSummaryMapper dischargeSummaryMapper;
    @Autowired
    IDischargeSummaryMedicineService medicineService;
    @Resource
    PatientMapper patientMapper;
    @Autowired
    IMessageService messageService;
    @Resource
    UserMapper userMapper;

    /**
     * 新增出院总结
     * @param dischargeSummary       实体对象
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addDischargeSummary(DischargeSummaryFrom dischargeSummary) throws Exception {
        DischargeSummary summary  = dischargeSummaryMapper.getSummaryByPatientId(dischargeSummary.getPatientId());
        if (summary != null){
            throw new Exception("患者已存在出院总结");
        }

        List<DischargeSummaryMedicine> medicineList = dischargeSummary.getMedicines();
        DischargeSummary dis = new DischargeSummary();
        dis.setDischargeTime(new Date());
        BeanUtils.copyProperties(dischargeSummary,dis);
        this.save(dis);
        medicineService.addMedicineSummary(medicineList,dis.getDischargeSummaryId());
        return dis.getDischargeSummaryId();
    }

    /**
     * 查询出院总结
     * @param pageNumber            页码
     * @param pageSize              大小
     * @param dischargeSummaryId    出院总结ID
     * @param patientId             病患ID
     * @return
     */
    @Override
    public Result dischargeSummaryList(Integer pageNumber, Integer pageSize, Integer dischargeSummaryId, Integer patientId) {
        if (pageNumber.equals(1)){
            pageNumber = 0;
        }else {
            pageNumber = pageNumber -1 * pageSize;
        }
        List<DischargeSummaryVo> list = dischargeSummaryMapper.getSummaryList(pageNumber,pageSize,dischargeSummaryId, patientId);
        Integer count = dischargeSummaryMapper.getCount(patientId);
        Integer pages = count/pageSize;
        Integer sum2 = count % pageSize;
        if (sum2 != 0){
            pages = pages +1;
        }

        List<DischargeSummaryVo> list2= new ArrayList<>();
        for (DischargeSummaryVo summaryVo: list){
            List<DischargeSummaryMedicine> medicineList = summaryVo.getMedicines();
            if (medicineList.get(0).getMedicineId() == null){
                summaryVo.setMedicines(null);
            }
            list2.add(summaryVo);
        }

        PageInfo<DischargeSummaryVo> pageInfo = new PageInfo<>(list2);
        pageInfo.setTotal(count);
        pageInfo.setPages(pages);
        if (pageNumber.equals(pages)){
            pageInfo.setIsLastPage(false);
        }else {pageInfo.setIsLastPage(true);}
        return Result.success(pageInfo);
    }

    /**
     * 更新出院总结
     * @param dischargeSummaryFrom          实体对象
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateDischargeSummary(DischargeSummaryFrom dischargeSummaryFrom) throws Exception {
        if (dischargeSummaryFrom.getDischargeSummaryId() == null || dischargeSummaryFrom.getUpdatedUserId() == null){
            throw new Exception(Constant.KEY_ID);
        }
        //判断此总结是否已经签字，签字后不允许修改
        DischargeSummary summary = dischargeSummaryMapper.getById(dischargeSummaryFrom.getDischargeSummaryId());
        if (summary.getSignUserId() != null){
            throw new Exception("已签字的总结不允许修改");
        }


        DischargeSummary dis = new DischargeSummary();
        dis.setUpdatedTime(new Date());
        BeanUtils.copyProperties(dischargeSummaryFrom,dis);
        if (dischargeSummaryFrom.getSignUserId() != null){
            dis.setSignTime(new Date());
        }
        boolean flag = this.updateById(dis);
        log.info("出院总结ID："+dis.getDischargeSummaryId());

        //如修改了带的药物，先删除原来的药物，在将此次药物存入
        List<DischargeSummaryMedicine> medicineList = dischargeSummaryFrom.getMedicines();
        medicineService.deleteMedicineSummary(dis.getDischargeSummaryId());
        if (medicineList != null) {
            medicineService.addMedicineSummary(medicineList, dis.getDischargeSummaryId());
        }

        return dis.getDischargeSummaryId();
    }

    /**
     * 出院总结--医生签字
     * @param dischargeSummaryId
     * @param userPass
     */
    @Override
    public Integer dischargeSignature(Integer dischargeSummaryId, String userPass) throws Exception {
        //当前登录用户可能是医生，护士等。
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        Integer uid = JwtTokenUtil.decodeTokenUserId(request.getHeader("token"));
        User user = userMapper.getUserByPass(uid, HeatUtil.md5(userPass));
        if (user == null){throw new Exception("密码错误");}

        DischargeSummary dischargeSummary = dischargeSummaryMapper.selectById(dischargeSummaryId);
        if (dischargeSummary.getSignUserId() != null){ throw new Exception("签字失败，已被签字了"); }

        dischargeSummary.setSignUserId(uid);
        dischargeSummary.setSignTime(new Date());
        dischargeSummaryMapper.updateById(dischargeSummary);
        return uid;
    }



}
